﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CaptchaGen;
using RentHouse.Common;
using RentHouse.DTO;
using RentHouse.IService;

namespace RentHouse.Admin.Controllers
{  
    public class HomeController : Controller
    {
        private readonly ILoginService _loginService;
        public HomeController(ILoginService loginService)
        {
            this._loginService = loginService;
        }

        public ActionResult Index()
        {
         
            return RedirectToAction("Index", "Main");
        }
        public ActionResult GetVerCode()
        {
          var code=  CommonHelper.CreateVerifyCode(4);
            TempData["code"] = code;
            System.IO.MemoryStream ms = ImageFactory.GenerateImage(code, 60, 100, 15, 20);
            return File(ms,"image/jpeg");
        }

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginDTO loginDTO)
        {
            if (!ModelState.IsValid)
            {   
                return Json(new AjaxResult(ResultState.Error, "登录失败"));
            }
            else
            {
                //如果校验通过处理登录流程
                if (loginDTO.VerCode != TempData["code"].ToString())
                {
                    return Json(new AjaxResult(ResultState.Error, "验证码输入错误"));
                }
                var result = _loginService.GetLogin(loginDTO);
             
                if (result.State==ResultState.Success)
                {
                    //string hostUrl = "";
                    //string pathUrl = "";
                    //hostUrl = Request.UrlReferrer == null ? Request.Url.Host : Request.UrlReferrer.Host;
                    //hostUrl = "http://" + hostUrl;
                    //pathUrl = Request.UrlReferrer == null ? "/" : Request.UrlReferrer.PathAndQuery;
                    //string reUrl = hostUrl + pathUrl;
                    //Response.Redirect(reUrl);
                return Json(_loginService.GetLogin(loginDTO));

                }
                else
                {
                    ModelState.AddModelError("", result.ErrorMessage);
                }
                return Json(_loginService.GetLogin(loginDTO));

            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
            //Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            return RedirectToAction("Login");

           
        
        }


    }
}